package org.dromara.knowledgebase.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import lombok.NonNull;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.ObjectUtils;
import org.dromara.knowledgebase.core.document.BaseDocument;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.data.elasticsearch.core.event.BeforeConvertCallback;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;

public class BeforeConvertCallbackHandler<T> implements BeforeConvertCallback<T> {


    @NonNull
    @Override
    public T onBeforeConvert(@NonNull T entity, @NonNull IndexCoordinates index) {
        try {
            if (entity instanceof BaseDocument baseEntity) {
                if (ObjectUtil.isNotNull(baseEntity.getDocumentId())) {//更新
                    Long current = ObjectUtils.notNull(baseEntity.getUpdateTime(), System.currentTimeMillis());
                    baseEntity.setUpdateTime(current);

                    Long createBy = ObjectUtils.notNull(baseEntity.getUpdateBy(), LoginHelper.getUserId());
                    baseEntity.setUpdateBy(createBy);
                }else { //插入
                    Long current = ObjectUtils.notNull(baseEntity.getCreateTime(), System.currentTimeMillis());
                    baseEntity.setCreateTime(current);
                    baseEntity.setUpdateTime(current);

                    Long createBy = ObjectUtils.notNull(baseEntity.getCreateBy(), LoginHelper.getUserId());
                    baseEntity.setCreateBy(createBy);
                    baseEntity.setUpdateBy(createBy);
                }
                return entity;
            } else {
                throw new ServiceException("文档实体必须继承BaseDocument");
            }
        } catch (Exception e) {
            throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);
        }
    }
}
